import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/task.dart';
import '../models/member.dart';
import '../providers/task_provider.dart';
import '../providers/member_provider.dart';
import './edit_task_dialog.dart';

class TaskCard extends StatelessWidget {
  final Task task;
  final VoidCallback? onDragStarted;
  final Function(DraggableDetails)? onDragEnd;

  const TaskCard({
    super.key, 
    required this.task,
    this.onDragStarted,
    this.onDragEnd,
  });

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final cardSize = screenSize.width / 5;
    final memberProvider = Provider.of<MemberProvider>(context);

    return MouseRegion(
      cursor: SystemMouseCursors.grab,
      child: Draggable<Task>(
        data: task,
        onDragStarted: onDragStarted,
        onDragEnd: onDragEnd,
        feedback: Material(
          elevation: 4.0,
          child: SizedBox(
            width: cardSize,
            height: cardSize,
            child: Card(
              color: task.color.withOpacity(0.8),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      task.title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
        childWhenDragging: Opacity(
          opacity: 0.3,
          child: _buildTaskCard(context, cardSize, memberProvider),
        ),
        child: _buildTaskCard(context, cardSize, memberProvider),
      ),
    );
  }

  Widget _buildTaskCard(BuildContext context, double cardSize, MemberProvider memberProvider) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      color: task.color.withOpacity(0.1),
      child: SizedBox(
        width: cardSize,
        height: cardSize,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题行
              Row(
                children: [
                  Checkbox(
                    value: task.isCompleted,
                    onChanged: Provider.of<TaskProvider>(context).canCompleteTask(context, task)
                        ? (bool? value) {
                            Provider.of<TaskProvider>(context, listen: false)
                                .toggleTaskCompletion(task);
                          }
                        : null,
                  ),
                  Expanded(
                    child: Text(
                      task.title,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        decoration: task.isCompleted ? TextDecoration.lineThrough : null,
                        color: task.isCompleted ? Colors.grey : null,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),

              // 描述
              Expanded(
                child: Text(
                  task.description,
                  style: const TextStyle(fontSize: 14),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              const Divider(),

              // 底部信息
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 创建时间
                  Row(
                    children: [
                      const Icon(Icons.access_time, size: 14),
                      const SizedBox(width: 4),
                      Text(
                        '创建: ${_formatDate(task.createdAt)}',
                        style: const TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),

                  // 截止日期
                  if (task.dueDate != null) ...[
                    Row(
                      children: [
                        const Icon(Icons.calendar_today, size: 14),
                        const SizedBox(width: 4),
                        Text(
                          '截止: ${_formatDate(task.dueDate!)}',
                          style: TextStyle(
                            fontSize: 12,
                            color: _isOverdue(task.dueDate!) ? Colors.red : null,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 4),
                  ],

                  // 分配信息
                  if (task.assignedTo != null)
                    FutureBuilder<Member?>(
                      future: memberProvider.getMember(task.assignedTo!),
                      builder: (context, snapshot) {
                        if (snapshot.connectionState == ConnectionState.waiting) {
                          return const SizedBox(
                            height: 20,
                            child: Center(
                              child: SizedBox(
                                width: 12,
                                height: 12,
                                child: CircularProgressIndicator(strokeWidth: 2),
                              ),
                            ),
                          );
                        }
                        if (snapshot.hasData && snapshot.data != null) {
                          return Row(
                            children: [
                              const Icon(Icons.person, size: 14),
                              const SizedBox(width: 4),
                              Text(
                                '负责: ${snapshot.data!.name}',
                                style: const TextStyle(fontSize: 12),
                              ),
                            ],
                          );
                        }
                        if (snapshot.hasError) {
                          return const Row(
                            children: [
                              Icon(Icons.error_outline, size: 14, color: Colors.red),
                              SizedBox(width: 4),
                              Text(
                                '加���失败',
                                style: TextStyle(fontSize: 12, color: Colors.red),
                              ),
                            ],
                          );
                        }
                        return const SizedBox.shrink();
                      },
                    ),

                  const SizedBox(height: 4),

                  // 优先级和操作按钮
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                        decoration: BoxDecoration(
                          color: _getPriorityColor(task.priority),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          _getPriorityText(task.priority),
                          style: const TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          if (Provider.of<TaskProvider>(context).canEditTask(context, task))
                            IconButton(
                              icon: const Icon(Icons.edit, size: 18),
                              padding: EdgeInsets.zero,
                              constraints: const BoxConstraints(),
                              onPressed: () {
                                showDialog(
                                  context: context,
                                  builder: (context) => EditTaskDialog(task: task),
                                );
                              },
                            ),
                          const SizedBox(width: 8),
                          if (Provider.of<TaskProvider>(context).canDeleteTask(context, task))
                            IconButton(
                              icon: const Icon(Icons.delete, size: 18),
                              padding: EdgeInsets.zero,
                              constraints: const BoxConstraints(),
                              onPressed: () {
                                Provider.of<TaskProvider>(context, listen: false)
                                    .deleteTask(task.id);
                              },
                            ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.month}-${date.day}';
  }

  bool _isOverdue(DateTime dueDate) {
    return !task.isCompleted && dueDate.isBefore(DateTime.now());
  }

  Color _getPriorityColor(TaskPriority priority) {
    switch (priority) {
      case TaskPriority.low:
        return Colors.green;
      case TaskPriority.medium:
        return Colors.orange;
      case TaskPriority.high:
        return Colors.red;
    }
  }

  String _getPriorityText(TaskPriority priority) {
    switch (priority) {
      case TaskPriority.low:
        return '低';
      case TaskPriority.medium:
        return '中';
      case TaskPriority.high:
        return '高';
    }
  }
} 